﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Akso.Authorization;
using Akso.Entities;
using Akso.Orders.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace Akso.Orders
{
    [AbpAuthorize(AppPermissions.Pages_StudentModule_Orders)]
    public class OrderAppService: AbpZeroTemplateAppServiceBase, IOrderAppService
    {
        private readonly IRepository<StudentOrder, Guid> _ordersRepository;

        public OrderAppService(IRepository<StudentOrder, Guid> ordersRepository)
        {
            _ordersRepository = ordersRepository;

        }
        #region 查询数据
        /// <summary>
        /// 根据输入条件进行数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private IQueryable<StudentOrder> getQuery(GetOrdersInput input)
        {
            var query = _ordersRepository.GetAll()
                .WhereIf(
                    !input.Filter.IsNullOrWhiteSpace(),
                    t =>
                        t.OrderCode.Contains(input.Filter) ||
                        t.SName.Contains(input.Filter)
                );
            return query;
        }
        public async Task<ListResultDto<OrderListDto>> GetObjects(GetOrdersInput input)
        {
            var query = getQuery(input);
            var dataCount = await query.CountAsync();
            var data = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();

            return new PagedResultDto<OrderListDto>(
                dataCount,
                data.MapTo<List<OrderListDto>>()
                );
        }
        #endregion

        public async Task<GetOrderForEditOutput> GetObjectForEdit(NullableIdDto<Guid> input)
        {
            var output = new GetOrderForEditOutput
            {

            };

            if (!input.Id.HasValue)
            {
                //Creating a new object
                output.Order = new OrderEditDto();
            }
            else
            {
                //Editing an existing object
                var existingObject = await _ordersRepository.GetAsync(input.Id.Value);

                output.Order = existingObject.MapTo<OrderEditDto>();
            }

            return output;
        }
    }
}
